<?php

/** Cms_Resource_Administrator_Item */
if (!class_exists('Cms_Resource_Administrator_Item')) {
    require_once dirname(__FILE__) . '/Administrator/Item.php';
}

/** Cms_Resource_AdministratorGroup */
if (!class_exists('Cms_Resource_AdministratorGroup')) {
    require_once dirname(__FILE__) . '/AdministratorGroup.php';
}

/**
 * Cms_Resource_Administrator
 *
 * @category   Cms
 * @package    Cms_Model_Resource
 */
class Cms_Resource_Administrator extends BIS_Model_Resource_Db_Table_Abstract implements Cms_Resource_Administrator_Interface
{
    protected $_name    = 'admin';
    protected $_primary  = 'adminId';
    protected $_rowClass = 'Cms_Resource_Administrator_Item';

    protected $_referenceMap = array(
        'Group' => array(
            'columns' => 'adminGroupId',
            'refTableClass' => 'Cms_Resource_AdministratorGroup',
            'refColumns' => 'adminGroupId',
        )
    );

    public function getAdministratorById($id)
    {
        return $this->find($id)->current();
    }

     public function getAdministrators($data= array())
    {

        $select = $this->select();

        if (isset($data['order'])) {
            $select->order($data['order']);
        }

	if (isset($data['page'])) {
		$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
		$paginator = new Zend_Paginator($adapter);
		$paginator->setItemCountPerPage($data['limit'])
	          	  ->setCurrentPageNumber((int) $data['page']);
		return $paginator;
	}
        
        return $this->fetchAll($select);

    }

     public function getAdministratorByUsername($username, $ignoreAdministrator=null)
    { 
         $select = $this->select();
         $select->where('username = ?', $username);

        if (null !== $ignoreAdministrator) {
            $select->where('username != ?', $ignoreAdministrator->username);
        }

        return $this->fetchRow($select);
    }

     public function getAdministratorByEmail($email, $ignoreAdministrator=null)
    {
         $select = $this->select();
         $select->where('email = ?', $email);

        if (null !== $ignoreAdministrator) {
            $select->where('email != ?', $ignoreAdministrator->email);
        }

        return $this->fetchRow($select);
    }

    public function getTotalAdministratorsByGroupId($groupId) {

        $select = $this->select()
                ->from('admin',array('COUNT(adminGroupId) AS total'))
                ->where('adminGroupId = ?', $groupId);

        $row = $this->fetchRow($select);

        return $row->total;

    }

    public function getTotalAdministratorsByBranchId($branchId) {


        $select = $this->select()
                ->from('admin',array('COUNT(branchId) AS total'))
                ->where('branchId = ?', $branchId);

        $row = $this->fetchRow($select);

        return $row->total;

    }
    
}